import axios from "axios";
import ElMessage from "element-plus";
import router from "../router";

// 响应拦截器
axios.interceptors.response.use(success => {
    //业务逻辑错误
    if (success.status && success.status === 200) {
        // 所有失败的情况
        if (success.data.code === 500 || success.data.code === 401) {
            ElMessage.error({message: success.data.message});
            return;

        }
        if (success.data.message) {
            ElMessage.success({message: success.data.message});
        }
    }
    return success.data;
}, error => {
    if (error.response.code === 504 || error.response.code === 404) {
        ElMessage.error({message: '服务器被吃了!'});
    } else if (error.response.code === 403) {
        ElMessage.error({message: '无权限!'});
    } else if (error.response.code === 401) {
        ElMessage.error({message: '未登录!'});
        router.replace('/');
    } else {
        if (error.response.data.message) {
            ElMessage.error({message: error.response.data.message});
        } else {
            alert('未知错误！')
            ElMessage.error({message: '位置错误!'});

        }
    }
    return;
})

let baseUrl = '';

//post请求
export const postRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${baseUrl}${url}`,
        data: params
    })
}